<template>
  <div>
    <NormalForm :enum-opt="enumopt" :formList="formList" :operateForm="queryForm" pageTitle="权益详情"
                @handleQuery="handleQuery"
                @handleReset="handleReset">
      <template slot="more-btn">
        <el-button plain type="info" @click="$router.back()">返回</el-button>
      </template>
    </NormalForm>
    <div class="g-card">
      <div style="display: flex;justify-content: space-between;padding: 20px 20px 0">
        <div style="width: 500px;display: flex;justify-content: space-between;font-size: 16px;align-items: center">
          <span>总计权益码: {{ totalNum.totalCoincertificateCode || 0 }}</span>
          <span>已领取权益码: {{ totalNum.totalGetCode || 0 }}</span>
          <span>已核销权益码: {{ totalNum.totalUseCode || 0 }}</span>
        </div>
        <div class="top-right">
          <el-button plain type="info" @click="importCancelledVisible = true">导入已核销权益码</el-button>
          <el-button type="primary" @click="importCouponVisible = true">导入权益码</el-button>
        </div>
      </div>
      <div style="padding: 16px 20px 20px 20px">
        <el-table :data="tableList" v-loading="loading" height="510px" style="width: 100%">
          <el-table-column align="center" label="权益码" min-width="160" prop="coincertificateCode"></el-table-column>
          <el-table-column align="center" label="卡密" min-width="140" prop="id"></el-table-column>
          <el-table-column align="center" label="权益名称" min-width="170" prop="batchName"
                           show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="激活开始时间" min-width="170"
                           prop="activateStartTime"></el-table-column>
          <el-table-column align="center" label="激活截止时间" min-width="170" prop="activateEndTime"></el-table-column>
          <el-table-column align="center" label="领取状态" prop="state">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.state == 0" class="el-tag-1" type="warning">待领取
              </el-tag>
              <el-tag v-if="scope.row.state == 1" class="el-tag-2" type="success">已领取
              </el-tag>
              <el-tag v-if="scope.row.state == 2" class="el-tag-3" type="info">已核销</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="领取时间" min-width="170" prop="getTime">
            <template slot-scope="{row}">
              {{ row.getTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="用户" min-width="170" prop="userName">
            <template slot-scope="{ row }">
              <div style="display: flex;align-items: center;justify-content: center">
                <img v-if="row.userAvatar" :src="row.userAvatar" alt=""
                     style="width:30px; height:30px;border-radius:50%;margin-right:6px">
                <span style="line-height: 30px">{{ row.userName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="手机号" prop="mobile" :min-width="160"></el-table-column>
          <el-table-column align="center" label="所属账号" prop="sysUserName" :min-width="160"></el-table-column>
          <el-table-column align="center" label="所属员工" prop="weUserName" :min-width="160"></el-table-column>
          <el-table-column :min-width="180" align="center" label="核销状态" prop="useState">
            <template slot-scope="scope">
              <div v-loading="scope.row.switchLoading">
                <el-switch v-model="scope.row.useState" v-hasPermi="['scrm:admin:couponInfo:updateUseState']"
                           :active-value="'1'" :disabled="+scope.row.state == 0"
                           :inactive-color="'#999999'"
                           :inactive-value="'0'" style="font-size: 12px" @change="updateState(scope.row, scope)">
                </el-switch>
                <span :style="scope.row.useState == '1' ? 'color:#082aff':'color:#999999;'"
                      style="margin-left: 8px">{{ scope.row.useState === '1' ? '已核销' : '未核销' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="核销时间" min-width="170" prop="useTime">
            <template slot-scope="{ row }">
              {{ row.useState === '1' ? row.useTime : "-" || '-' }}
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="toDel(scope.row)" :disabled="!(scope.row.state == 0 && scope.row.createCode == getUserId())">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total"
                          @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
      </div>
    </div>
    <import-coupon v-if="importCouponVisible" :visible.sync="importCouponVisible"></import-coupon>
    <import-cancelled v-if="importCancelledVisible" :visible.sync="importCancelledVisible"></import-cancelled>
    <el-dialog :visible.sync="confirmDeleteVisible" class="deleteDialog" title="删除确认" width="436px">
      <span class="deleteInfo"><i class="el-icon-question" style="color: #082aff"></i> 确认删除该权益码吗？</span>
      <div slot="footer">
        <el-button @click="confirmDeleteVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDeleteCustomer">确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '@/api/organization'
import * as http from '@/api/communityOperating/coupon'
import {getCouponInfoList} from '@/api/communityOperating/coupon.js'
import importCoupon from "./components/importCoupon.vue";
import importCancelled from "./components/importCancelled.vue";
import {permission} from "@/api/communityOperating/personalSop";
import {getUserId} from "@/utils/auth";

export default {
  name: 'CouponInfo',
  components: {
    importCoupon,
    importCancelled
  },
  data() {
    return {
      queryForm: {
        id: null,
        batchNo: '',
        mobile: null,
        sysUserId: '',
        weUserId: '',
        pageNum: 1,
        pageSize: 20,
      },
      pageNum: 1,
      pageSize: 20,
      formList: [
        {
          label: '手机号',
          value: '',
          prop: 'mobile',
          type: 'INPUT',
          emunName: '',
        },
        {
          label: '权益码',
          value: '',
          prop: 'coincertificateCode',
          type: 'INPUT',
          emunName: '',
        },
        {
          label: '所属账号',
          value: '',
          prop: 'sysUserId',
          type: 'SELECT',
          emunName: 'deptList',
          multiple: false,
        },
        {
          label: '所属员工',
          value: '',
          prop: 'weUserId',
          type: 'SELECT',
          emunName: 'userList',
          multiple: false,
        },
      ],
      enumopt: {
        userList: [],
        deptList: [],
      },
      loading: false,
      tableList: [],
      total: 0,
      totalNum: {
        totalCoincertificateCode: 0,
        totalGetCode: 0,
        totalUseCode: 0,
      },
      importCouponVisible: false,
      importCancelledVisible: false,
      confirmDeleteVisible: false,
      currentSelectRow: {},
    }
  },
  created() {
    this.queryForm.batchNo = this.$route.query.batchNo
    this.getUserList()
    this.queryDeptMsg()
    this.handleQuery()
  },
  methods: {
    getUserId,
    // 查询执行员工
    queryDeptMsg() {
      this.enumopt.deptList = []
      let obj = {
        name: "",
        deptId: null,
        authFlag: "Y",
      };
      permission(obj).then((res) => {
        if (res.code === 200 && res.data.length) {
          res.data.forEach((item) => {
            this.enumopt.deptList.push({
              id: item.userId,
              dictValue: item.userId,
              dictLabel: item.userName,
              // children: [],
            });
          });
        }
      })
    },
    getUserList() {
      this.enumopt.userList = []
      api.getList({
        name: '',
        department: '',
        pageNum: 1,
        pageSize: 99999,
        isActivate: '',
      })
        .then(({rows}) => {
          this.enumopt.userList = rows.map(item => {
            return {
              ...item,
              dictLabel: item.name,
              dictValue: item.userId,
            }
          })
        })
    },
    handleQuery() {
      this.pageNum = 1
      this.getListFn()
    },
    getListFn() {
      this.tableList = []
      this.loading = true;
      let obj = {
        batchNo: this.queryForm.batchNo,
        pageNum: this.queryForm.pageNum,
        pageSize: this.queryForm.pageSize,
        mobile: this.queryForm.mobile,
        weUserId: this.queryForm.weUserId,
        sysUserId: this.queryForm.sysUserId,
        coincertificateCode: this.queryForm.coincertificateCode,
      }
      getCouponInfoList(obj).then(res => {
        if (res.code === 200) {
          this.tableList = res.rows || []
          this.total = res.total || 0
        }
        this.loading = false;
      }).catch(() => this.loading  = false)
      http.getCouponInfoSum({batchNo: this.$route.query.batchNo}).then(res => {
        if (res.code === 200) {
          this.totalNum = {
            totalCoincertificateCode: res.data.totalCoincertificateCode || 0,
            totalUseCode: res.data.totalUseCode || 0,
            totalGetCode: res.data.totalGetCode || 0,
          }
        }
      })
    },
    handleSizeChange(val) {
      this.pageNum = 1
      this.pageSize = val
      this.getListFn()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      console.log(this.pageNum)
      this.getListFn()
    },
    handleReset() {
      this.queryForm = {
        batchNo: this.$route.query.batchNo,
        mobile: '',
        sysUserId: '',
        weUserId: '',
        id: '',
        pageNum: 1,
        pageSize: 20,
      };
      this.getListFn()
    },
    updateState(row, scope) {
      if(row.state == 0) return
      this.tableList[scope.$index].switchLoading = true
      this.$set(this.tableList, scope.$index, row)
      let state = row.useState
      this.$confirm('确认修改该权益码状态吗？', '权益码核销', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row, 'row')
        let obj = {
          useState: row.useState,
          coincertificateCode: row.coincertificateCode
        }
        http.updateCouponCodeState(obj).then(res => {
          if (res.code == 200) this.getListFn()
          this.tableList[scope.$index].switchLoading = false
          this.$set(this.tableList, scope.$index, row)
        }).catch(() => {
          this.tableList[scope.$index].switchLoading = false
          this.$set(this.tableList, scope.$index, row)
          row.useState = state == '1' ? '0' : '1'
        })
      }).catch(() => {
        this.tableList[scope.$index].switchLoading = false
        this.$set(this.tableList, scope.$index, row)
        row.useState = state == '1' ? '0' : '1'
      });
    },
    toDel(row) {
      if(row.state != 0) return
      if(row.createCode != getUserId()) return;
      this.confirmDeleteVisible = true;
      this.currentSelectRow = row;
    },
    handleDeleteCustomer() {
      http.deleteCouponCode({id: this.currentSelectRow.coincertificateId}).then(res => {
        this.confirmDeleteVisible = false
        if (res.code == 200) {
          this.handleQuery()
          this.$message.success('删除成功！')
        }
      }).catch(() => {
        this.confirmDeleteVisible = false
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import '../../../styles/base.scss';

::v-deep .el-table th.el-table__cell.is-leaf, .el-table td.el-table__cell {
  border-bottom: none !important;
}

::v-deep .el-table .el-table__header-wrapper th {
  background-color: #f8f8f9 !important;
}


::v-deep.el-tag-2 {
  background: rgba(255, 173, 58, 0.1) !important;
  border-radius: 3px !important;
  border: 1px solid #FFAD3A !important;
  color: #FFAD3A !important;
}

::v-deep.el-tag-1 {
  background: rgba(252, 88, 48, 0.1) !important;
  border-radius: 3px !important;
  border: 1px solid #082aff !important;
  color: #082aff !important;
}

::v-deep.el-tag-3 {
  background: rgba(20, 213, 149, 0.1) !important;
  border-radius: 3px !important;
  border: 1px solid rgba(20, 213, 149, 1) !important;
  color: #14D595 !important;
}

::v-deep {
  .el-loading-spinner {
    margin-top: -11px !important;
  }

  .el-loading-spinner .circular {
    width: 22px !important;
    height: 22px !important;
  }
}
</style>
